"""
菜单类
"""
import requests, time, os
from lxml import etree
from end import End
from board import Board
from libs import getDomain

class Menu():
    def __init__(self):
        response = requests.get('http://adnmb.com/')
        html = etree.HTML(response.text)
        self.boards = html.xpath('//*[@id="h-menu-content"]/li[@class="uk-parent"]/ul/li')
        self.page = 0
        self.url = response.url

    def getAction(self, action):
        if action == 'up' or action == 'u':
            self.page = self.page - 1 if self.page > 0 else 0
            return self
        elif action == 'down' or action == 'd':
            self.page = self.page + 1 if (self.page + 1) * 10 < len(self.boards) else self.page
            return self
        elif action.isdigit() and int(action) < len(self.boards):
            domain = getDomain(self.url)
            url = domain + self.boards[int(action)].xpath('./a/@href')[0]
            return Board(url, self)
        elif action == 'f':
            return Menu()
    
    def show(self):

        # 解析错误
        if len(self.boards) == 0 :
            print("无法解析！请按f重试或按q退出。")
            return True

        # 分页显示
        if self.page * 10 + 9 > len(self.boards):
            pageEnd = len(self.boards)
        else:
            pageEnd = self.page * 10 + 10
        pageStart = self.page * 10

        for i in range(pageStart, pageEnd):
            print(str(i) + '. ' + self.boards[i].xpath('.//text()')[1].strip())
        
        print('Up上一页/Down下一页')
        return True


if __name__ == "__main__":
    menu = Menu()
    menu.show()
    menu.getAction('0')